<!-- 在线巡护 -->
<script setup>
import { reactive, toRefs, ref, onMounted, createVNode, render, onBeforeUnmount } from 'vue';
import { LocationFilled, ArrowRightBold, ArrowLeftBold } from '@element-plus/icons-vue';
import { ElButton, ElInput, ElOption, ElSelect, ElTable, ElTableColumn, ElIcon, ElTooltip } from 'element-plus';
import PATROL_ICON from '../../../assets/images/icon/人员.png';
import ON_LINE_ICON from '../../../assets/images/icon/巡护人员.png';
import CommonMapPopup from '../common/CommonMapPopup.vue';
import {
  ADD_MAP_POINTS_IMAGE,
  GET_MAPBOX_MAP,
  REMOVE_LAYER,
  REMOVE_MAP_IMG,
  MAP_POINT_ONE,
  MAP_POPUP,
  CLEAR_POPUP_MAP,
} from '../common/common-map-fun';
import { layerGroupId } from '../common/common-map-info';

const props = defineProps({
  btnChecked: String,
});
const { btnChecked } = toRefs(props);
const emit = defineEmits(['handleWindowWidth']);
let map = null;
let vNodePopup = null;
const openShow = ref(false);
const showModal = ref(true);
const patrolOption = ref([
  {
    id: '56235666618662912',
    roleName: '研发',
  },
  {
    id: '55105873600720896',
    roleName: '监测部门',
  },
  {
    id: '55102663615983616',
    roleName: '三图信息技术',
  },
  {
    id: '54791447039328256',
    roleName: '测试部门',
  },
  {
    id: '52564990628151296',
    roleName: '数字孪生',
  },
  {
    id: '52513707154161664',
    roleName: '积木科技',
  },
  {
    id: '52511870262919168',
    roleName: '西安市三图科技有限',
  },
  {
    id: '52219207487758336',
    roleName: '图灵普惠',
  },
  {
    id: '47091773642629120',
    roleName: '林业站',
  },
]);
const tableList = ref([]);
const tableListAll = ref([]);
const checkedPoint = ref({});
const tableColum = ref([
  { label: '巡护人员', value: 'username' },
  { label: '管护站', value: 'positionNames' },
  { label: '位置', value: '' },
]);

const selectParams = reactive({
  deptNames: '全部', //管护单位
  username: '',
  userAccount: '',
});

onMounted(() => {
  if (btnChecked.value == '在线巡护') {
    map = GET_MAPBOX_MAP();

    onlinePatrolApi();
  }
});

const onChangeOption = (e) => {
  if (e == '') {
    selectParams.deptNames = '全部';

    if (selectParams.userAccount !== '' || selectParams.username !== '') {
      handleSelectQuery();
    } else {
      onlinePatrolApi();
    }
  }
};

// 展开/收缩
const handleOpenLined = (item) => {
  if (item == '展开') {
    openShow.value = true;
    emit('handleWindowWidth', '40.9375rem');
    tableColum.value.splice(2, 0, { label: '联系方式', value: 'userAccount' });
  } else {
    tableColum.value.splice(2, 1);
    openShow.value = false;
    emit('handleWindowWidth', '35.9375rem');
  }
};

/*
 *@description: 在线巡护人员
 */
const onlinePatrolApi = () => {
  const data = [
    {
      userId: '56182170913492992',
      userCreatedDate: '2023-09-04 13:48:53',
      userAvatar: '56182170913492992/202309/7892f997fcb740d2825bb26bf972b17a.jpg',
      userAccount: '18740305372',
      username: '杨一',
      deptNames: ['林业站'],
      patrolLen: 87,
      location: {
        x: 34.22790858019918,
        y: 108.90302958133346,
        z: 'NaN',
        m: 'NaN',
      },
      latestOnlineTime: '2024-01-05 16:59:13',
      posts: [
        {
          id: '47484877704978432',
          roleName: '科长',
          level: 2,
          parentId: '47091773642629120',
          parent: {
            id: '47091773642629120',
            roleName: '林业站',
            level: 1,
            parentId: '1',
            parent: null,
            position: '林业站',
          },
          position: '林业站-科长',
        },
      ],
    },
  ];

  for (let i = 0; i < data.length; i++) {
    const el = data[i];

    el['positionNames'] = el.deptNames.join('、');
  }

  tableListAll.value = data;

  tableList.value = data;

  patrol_point_all();
};

// 初始展示在线巡护列表人所有人员位置
const patrol_point_all = () => {
  const layerId = layerGroupId.MAP_POINT_LAYER;

  ADD_MAP_POINTS_IMAGE(layerId, tableList.value, '巡护人员', ON_LINE_ICON, map, 1, 7);

  map.off('click', (e) => mapCallBack(e));

  getMapFeatures();
};

// 清除坐标图层
const clear_map_layer = () => {
  const layerId = layerGroupId.MAP_POINT_LAYER;

  tableList.value.map((item) => {
    REMOVE_LAYER(layerId + String(item.userId));
    REMOVE_MAP_IMG(layerId + String(item.userId));
  });
};

// 清除单点坐标图层
const clear_map_point_layer = () => {
  const layerId = layerGroupId.MAP_POINT_LAYER_LIGHT;

  REMOVE_LAYER(layerId + String(checkedPoint.value?.userId));
  REMOVE_MAP_IMG(layerId + String(checkedPoint.value?.userId));
};

// 单人位置point
const handlePoint = (item, type) => {
  CLEAR_POPUP_MAP();

  const layerId = layerGroupId.MAP_POINT_LAYER_LIGHT;

  clear_map_point_layer();

  if (type) {
    MAP_POINT_ONE(layerId, item, '巡护人员', ON_LINE_ICON, map);
    checkedPoint.value = item;
  } else {
    checkedPoint.value = {};
    map.setZoom(7);
  }
};

// 查询属性信息
const getMapFeatures = () => {
  // 解除绑定需要加绑定的函数，不然无法解绑
  map.off('click', mapCallBack);

  map.on('click', mapCallBack);
};

// 地图点击查询
const mapCallBack = (e) => {
  const features = map.queryRenderedFeatures(e.point);

  vNodePopup = null;

  if (features.length && 'layerKey' in features[0].properties && features[0].properties.layerKey == '巡护人员') {
    vNodePopup = createVNode(CommonMapPopup, {
      popupInfo: features[0].properties,
      title: '人员信息',
      mainLabel: ['巡护员:', '联系方式:', '经纬度:', '平面坐标:', '定位时间:', '管护站:', '创建时间:'],
      type: '巡护人员',
    });

    let elpopup = document.createElement('div');

    elpopup.className = 'popup_';
    elpopup.id = 'popup_id';
    render(vNodePopup, elpopup);
    features[0].properties['longitude'] = JSON.parse(features[0].properties?.location)?.y;
    features[0].properties['latitude'] = JSON.parse(features[0].properties?.location)?.x;
    MAP_POPUP(features, elpopup);
  }
};

// 搜索
const handleSelectQuery = () => {
  const selectArr = fuzzyQuery();

  clear_map_layer();
  clear_map_point_layer();
  CLEAR_POPUP_MAP();

  showModal.value = true;
  tableList.value = selectArr;
  patrol_point_all();
};

/**
 * 使用test方法实现精准查询
 * @return {Array}查询的结果
 */
function fuzzyQuery() {
  let resArr = [];

  tableListAll.value.map((item) => {
    let flag = true;

    for (let key in selectParams) {
      if (
        item[key] !== selectParams[key] &&
        !['全部'].includes(selectParams[key]) &&
        ![''].includes(selectParams[key]) &&
        !item.deptNames.includes(selectParams[key])
      ) {
        flag = false;
        break;
      }
    }

    if (flag) {
      resArr.push(item);
    }
  });

  return resArr;
}

onBeforeUnmount(() => {
  map.off('click', mapCallBack);
});
</script>
<template>
  <div class="online_root">
    <div class="select_">
      <div>
        <p>管护单位</p>
        <ElSelect
          v-model="selectParams.deptNames"
          placeholder="请选择管护单位"
          clearable
          @change="(e) => onChangeOption(e)"
        >
          <ElOption v-for="item in patrolOption" :key="item.roleName" :label="item.roleName" :value="item.roleName" />
        </ElSelect>
      </div>
      <div>
        <p>人员姓名</p>
        <ElInput v-model.trim="selectParams.username" placeholder="请输入人员姓名" maxlength="22" />
      </div>
      <div>
        <p>联系方式</p>
        <ElInput v-model.trim="selectParams.userAccount" placeholder="请输入" maxlength="11" />
        <ElButton type="primary" class="qr_" @click="handleSelectQuery()">确认</ElButton>
      </div>
    </div>
    <div class="table_main table_">
      <ElTable
        :data="tableList"
        :header-cell-style="{
          color: '#D0F2FF',
          background: 'rgba(25, 66, 117,0.4)',
        }"
        class="table_border"
        :highlight-current-row="false"
      >
        <ElTableColumn type="index" width="55" label="序号" align="center" />
        <ElTableColumn
          v-for="(item, index) in tableColum"
          :key="index"
          :prop="item.value"
          :label="item.label"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div v-if="item.label == '巡护人员'" class="content_style img_style" :title="scope.row[item.value]">
              <p>
                <img :src="PATROL_ICON" /><span>{{ scope.row[item.value] }}</span>
              </p>
            </div>
            <span v-else class="content_style" :title="scope.row[item.value]">{{ scope.row[item.value] }}</span>

            <div v-if="item.label == '位置'" class="point_icon">
              <ElIcon
                v-if="checkedPoint?.userId == scope.row.userId"
                class="point_true"
                @click="handlePoint(scope.row, false)"
                ><LocationFilled />
              </ElIcon>
              <ElIcon
                v-if="checkedPoint?.userId !== scope.row.userId"
                class="point_false"
                @click="handlePoint(scope.row, true)"
                ><LocationFilled />
              </ElIcon>
            </div>
          </template>
        </ElTableColumn>
      </ElTable>
    </div>

    <!-- 展开收缩按钮 -->
    <div class="outLined">
      <ElTooltip v-if="!openShow" content="展开" effect="light" placement="right-start">
        <ElIcon @click="handleOpenLined('展开')"><ArrowRightBold /></ElIcon>
      </ElTooltip>
      <ElTooltip v-if="openShow" content="收缩" effect="light" placement="right-start">
        <ElIcon @click="handleOpenLined('收缩')"><ArrowLeftBold /></ElIcon>
      </ElTooltip>
    </div>
  </div>
</template>

<style scoped lang="scss">
.online_root {
  .select_ {
    margin-top: 21px;
    div {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      p {
        width: 80px;
        margin-right: 12px;
        text-align: right;
      }
      .qr_ {
        margin-bottom: 6px;
        margin-left: 14px;
      }
    }

    :deep(.el-input) {
      width: 286px;
    }
    :deep(.el-input__inner) {
      color: #d0f2ff;
    }
    :deep(.el-input__wrapper) {
      background: none;
      box-shadow: 0 0 0 0.0625rem rgba(228, 228, 228, 0.2) inset;
    }
    :deep(.el-select) {
      width: 80%;
    }
  }

  .table_main {
    .content_style {
      color: #d0f2ff;
      font-size: 16px;
    }

    .img_style {
      display: flex;
      align-items: center;
      justify-content: center;
      span {
        display: inline-block;
        width: 67px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
      }
    }

    .table_border {
      width: 100%;
      height: 450px;
      border-radius: 4px;
    }

    .point_icon {
      .el-icon {
        color: #66bbfd;
        font-size: 18px;
        cursor: pointer;
        &:hover {
          color: #ffffff;
        }
      }
      .point_true {
        color: #ffffff !important;
      }
    }

    :deep(.el-table td.el-table__cell div) {
      color: #fff;
    }
    :deep(.el-table) {
      background: rgba(25, 66, 117, 0.2) !important;
    }
    :deep(.el-table__empty-text) {
      color: #ffffff !important;
    }

    :deep(.el-table) {
      --el-table-border-color: rgba(25, 66, 117, 0.1) !important
      ;
    }
    :deep(.el-table__column-filter-trigger i) {
      color: #ffffff !important;
      font-size: 18px;
    }

    :deep(.el-table tr) {
      font-size: 16px;
      background: none !important;
    }
    :deep(tr:hover > td) {
      background-color: rgba(25, 66, 117, 0.6) !important;
    }
  }

  .outLined {
    position: absolute;
    top: 320px;
    right: -60px;
    z-index: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 75px;
    font-size: 24px;
    background: rgba(122, 171, 255, 0.56);
    border-radius: 0px 6px 6px 0px;
    cursor: pointer;
  }
}
</style>

<style lang="scss">
.mapboxgl-popup-close-button {
  top: 20px;
  right: 20px;
  color: #ffffff !important;
}
</style>
